import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jsoup.Jsoup
import java.io.IOException
import java.io.InputStream
import java.net.URL

class BitmapViewModel : ViewModel() {

    private val _bitmaps = MutableLiveData<List<Bitmap>>()
    val bitmaps: LiveData<List<Bitmap>> get() = _bitmaps

    private val _error = MutableLiveData<Boolean>()
    val error: LiveData<Boolean> get() = _error

    fun loadImages() {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                // Fetch Baidu homepage to get a list of image URLs
                val document = Jsoup.connect("https://www.baidu.com").get()
                val imageElements = document.select("img")
                val loadedBitmaps = imageElements.map { imageUrl ->
                    val url = imageUrl.attr("src")
                    if (url.endsWith(".jpg", true) || url.endsWith(".png", true)) {
                        loadImageBitmap(url)
                    } else {
                        null // Ignore images with other file extensions
                    }
                }.filterNotNull()

                _bitmaps.postValue(loadedBitmaps)
                _error.postValue(false)
            } catch (e: IOException) {
                e.printStackTrace()
                _error.postValue(true)
            }
        }
    }

    private fun loadImageBitmap(imageUrl: String): Bitmap {
        val inputStream: InputStream = URL(imageUrl).openStream()
        return BitmapFactory.decodeStream(inputStream)
    }
}
